﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Account
{
    /// <summary>
    /// 查询用户列表的中介者处理类
    /// </summary>
    public class QueryAccountHandler : IRequestHandler<QueryAccountCommand, ApiResult<List<AccountDTO>>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;

        public QueryAccountHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 查询用户列表的中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<AccountDTO>>> Handle(QueryAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<AccountDTO>> result = new ApiResult<List<AccountDTO>>();

            var query = accRepo.Query().Result; //select * from Acctable
            if (!string.IsNullOrEmpty(request.AccountName)) {//如果请求命令参数里,账号不为空,就根据账号查询
                query = query.Where(x=>x.AccountName.Contains(request.AccountName)); // select * from Acctable where AccountName like'%request.AccountName%'
            }
            if (!string.IsNullOrEmpty(request.RealName))
            {//如果请求命令参数里,账号不为空,就根据真实姓名查询
                query = query.Where(x => x.RealName.Contains(request.RealName)); // select * from Acctable where AccountName like'%request.AccountName%' and  RealName like '%requst.RealName%'
            }
            if (!string.IsNullOrEmpty(request.Phone))
            {//如果请求命令参数里,账号不为空,就根据手机号查询
                query = query.Where(x => x.Phone== request.Phone);
                // select * from Acctable where AccountName like'%request.AccountName%'
                // and  RealName like '%requst.RealName%'
                // and  Phone==Phone
            }

            var list = mapper.Map<List<AccountDTO>>(query.ToList());


            result.Msg = "查询账号列表成功!";
            result.Code = ApiEnums.Success;
            result.Data = list;

            return Task.FromResult(result);


        }
    }
}
